//
//  OpenSDK_PullDownView.m
//
//  Created by 涂俊 on 2018/7/17.
//  Copyright © 2018年 wang_ziwu. All rights reserved.
//

#import "OpenSDK_PullDownView.h"

#define VIEW_X(aView)            ((aView).frame.origin.x)
#define VIEW_Y(aView)            ((aView).frame.origin.y)
#define VIEW_HEIGHT(aView)       ((aView).frame.size.height)
#define VIEW_WIDTH(aView)        ((aView).frame.size.width)

#define AnimateTime 0.25f   // 下拉动画时间

#define MenuBorderMinMargin    10

@interface OpenSDK_PullDownView () <UITableViewDelegate, UITableViewDataSource>

/** 外部传入的列表数量和ui*/
@property (nonatomic, strong) id<UITableViewDataSource> tableDelegate;

@property (nonatomic, weak) UIView *anchorView;

@property (nonatomic, strong) UIView *contentView;
/** rect*/
@property (nonatomic, assign) CGRect anchorRect;

@end

@implementation OpenSDK_PullDownView
-(instancetype)init{
    self = [super init];
    if (self) {
        [self configUI];
    }
    return self;
}
#pragma mark - config
- (void)configUI{
    [self configDefault];
    [self configTable];
}
- (void)configDefault{
    self.menuCellHeight = 50;
    self.menuMaxHeight = 3 * self.menuCellHeight;//默认显示3格
    self.coverBgColor = [UIColor clearColor];
    self.menuBgColor  = [UIColor whiteColor];
    self.place = AnchorPlaceMiddle;
}
- (void)configTable{
    [self addSubview:self.contentView];
}

#pragma mark - lifeCycle
#pragma mark - delegate
//UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.tableDelegate tableView:tableView numberOfRowsInSection:section];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self.tableDelegate tableView:tableView cellForRowAtIndexPath: indexPath];
    return cell;
}
//UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.menuCellHeight;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消点击效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.blockSelectedMenu) {
        self.blockSelectedMenu(indexPath.row);
    }
    if (self.blockClose) {
        self.blockClose();
    }
    [self animateRemoveView];
}
// UIResponder点击列表外部的响应
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.blockClose) {
        self.blockClose();
    }
    [self animateRemoveView];
}

#pragma mark - actionFunction
- (void)refreshUI{
    [self.contentView removeFromSuperview];
    self.contentView = nil;
    [self addSubview:self.contentView];
    [self drawmTableFrame];
    [self.mTable reloadData];
}
#pragma mark - function
- (void)animateShowView:(BOOL) rotate {
    self.contentView.frame = CGRectMake(VIEW_X(self.contentView), VIEW_Y(self.contentView), VIEW_WIDTH(self.contentView), 0);
    [UIView animateWithDuration:AnimateTime animations:^{
        if (rotate) {
            //旋转anchorView
            self.anchorView.transform = CGAffineTransformMakeRotation(M_PI);
        }
        CGFloat height = [self calHeight];
        self.contentView.frame = CGRectMake(VIEW_X(self.contentView), VIEW_Y(self.contentView), VIEW_WIDTH(self.contentView), height);
    }];
}
- (void)animateRemoveView {
    [UIView animateWithDuration:AnimateTime animations:^{
        self.anchorView.transform = CGAffineTransformIdentity;
        self.contentView.frame = CGRectMake(VIEW_X(self.contentView), VIEW_Y(self.contentView), VIEW_WIDTH(self.contentView), 0);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (CGFloat) calHeight {
    CGFloat h = [self.tableDelegate tableView:self.mTable numberOfRowsInSection:0] * self.menuCellHeight;
    //最大高度围栏限制
    if (h > self.menuMaxHeight) {
        h = self.menuMaxHeight;
    }
    if (_additionalView != nil) {
        h += _additionalViewHeight;
    }
    return h;
}

#pragma mark - Private
- (void)drawmTableFrame{
    CGPoint layerAnchor = CGPointZero;
    CGPoint layerPosition = CGPointZero;
    CGFloat x = CGRectGetMidX(self.anchorRect);
    CGFloat y = 0;
    CGFloat h = [self calHeight];
    CGFloat w = self.menuWidth;
    if (self.place == AnchorPlaceMiddle) {
        //X中点位置：
        //居左：table右偏
        //居右：table左偏
        x = CGRectGetMidX(self.anchorRect);
        if (x > CGRectGetMidX(self.bounds)) {
            x = x - 3*w/4.f;
            layerAnchor.x = 1;
            layerPosition.x = x+w;
        } else {
            x = x - w/4.f;
            layerAnchor.x = 0;
            layerPosition.x = x;
        }
    } else if(self.place == AnchorPlaceLeft) {
        //x和anchor左对齐
        x = self.anchorRect.origin.x;
        layerAnchor.x = 0;
        layerPosition.x = x;
    } else {
        //x和anchor右对齐
        x = self.anchorRect.origin.x + self.anchorRect.size.width - w;
        layerAnchor.x = 0;
        layerPosition.x = x;
    }
    //围栏
    if (x<MenuBorderMinMargin) {
        x = MenuBorderMinMargin;
        layerPosition.x = x;
    }
    if (x+w>self.bounds.size.width) {
        x = self.bounds.size.width - w - MenuBorderMinMargin;
        layerPosition.x = x+w;
    }
    //Y中心位置，下拉
    y = CGRectGetMaxY(self.anchorRect);
    self.mTable.frame = CGRectMake(0, 0, w, h);
    layerAnchor.y = 0;
    layerPosition.y = y;
    self.contentView.frame = CGRectMake(x, y, w, h);
    //动画锚点
    self.contentView.layer.position = layerPosition;
    self.contentView.layer.anchorPoint = layerAnchor;
}

#pragma mark - Public
/**
 *  anchorView：下拉位置依赖视图
 *  tableDelegate:列表delegate(数量及ui展示)
 *  cellNibName:单元格的xib名
 *  cellReuseIdentifier:单元格的重用标识
 */
+ (instancetype)pullMenuAnchorView:(UIView *)anchorView
                     tableDelegate:(id<UITableViewDataSource>)delegate
                         menuWidth:(CGFloat)menuWidth
                       cellNibName:(NSString *)cellNibName
               cellReuseIdentifier:(NSString *)cellReuseIdentifier {
    OpenSDK_PullDownView *menuView = [[OpenSDK_PullDownView alloc] init];
    menuView.anchorView = anchorView;
    menuView.tableDelegate = delegate;
    menuView.menuWidth = menuWidth;
    menuView.frame = [UIScreen mainScreen].bounds;
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
    [window addSubview:menuView];
    menuView.anchorRect = [anchorView convertRect:anchorView.bounds toView:window];
    // 注册自定义cell(通过xib)
    [menuView.mTable registerNib:[UINib nibWithNibName:cellNibName bundle:nil] forCellReuseIdentifier:cellReuseIdentifier];
    return menuView;
}

+ (instancetype)pullMenuAnchorView:(UIView *)anchorView
                     tableDelegate:(id<UITableViewDataSource>)delegate
                         menuWidth:(CGFloat)menuWidth
                         cellClass:(Class)cellClass
               cellReuseIdentifier:(NSString *)cellReuseIdentifier {
    OpenSDK_PullDownView *menuView = [[OpenSDK_PullDownView alloc] init];
    menuView.anchorView = anchorView;
    menuView.tableDelegate = delegate;
    menuView.menuWidth = menuWidth;
    menuView.frame = [UIScreen mainScreen].bounds;
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
    [window addSubview:menuView];
    menuView.anchorRect = [anchorView convertRect:anchorView.bounds toView:window];
    // 注册自定义cell(通过class)
    [menuView.mTable registerClass:cellClass forCellReuseIdentifier:cellReuseIdentifier];
    return menuView;
}

- (void)show:(BOOL) rotateAnchorView {
    // 绘制控件
    [self refreshUI];
    // 下拉展示动画
    [self animateShowView:rotateAnchorView];
}

- (void)reloadMenu {
    //刷新列表
    [self.mTable reloadData];
    //刷新列表大小
    CGFloat w = self.menuWidth;
    CGFloat h = [self calHeight];
    self.mTable.frame = CGRectMake(0, 0, w, h);
    self.contentView.frame = CGRectMake(self.contentView.frame.origin.x, self.contentView.frame.origin.y, w, h);
}

#pragma mark - layzing
- (UITableView *)mTable{
    if (!_mTable) {
        _mTable = [[UITableView alloc] initWithFrame:CGRectZero
                                               style:UITableViewStylePlain];
        _mTable.delegate = self;
        _mTable.dataSource = self;
        _mTable.layer.cornerRadius = 3;
        _mTable.backgroundColor = self.menuBgColor;
        _mTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _mTable;
}
- (UIView *)contentView{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectZero];
        _contentView.layer.borderWidth = 0.5;
        _contentView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.clipsToBounds = true;
        [_contentView addSubview:self.mTable];
        if (_additionalView != nil) {
            _mTable.tableFooterView = _additionalView;
        }
    }
    return _contentView;
}

- (void)setCoverBgColor:(UIColor *)coverBgColor{
    _coverBgColor = coverBgColor;
    self.backgroundColor = self.coverBgColor;
}
- (void)setMenuBgColor:(UIColor *)menuBgColor{
    _menuBgColor = menuBgColor;
    self.mTable.backgroundColor = self.menuBgColor;
    [self refreshUI];
}
-(void)setAnchorRect:(CGRect)anchorRect{
    _anchorRect = anchorRect;
}

@end
